<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request, { SERVER_BASE_URL } from '@/utils/request.js'
import { Plus } from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  categoryTag: ''
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 定义商品状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '在售', value: 'ON_SALE' },
  { label: '下架', value: 'OFF_SALE' }
]

// 分类标签选项（实际项目中可能需要从后端获取）
const categoryOptions = ref([
  { label: '全部', value: '' },
  { label: '食品', value: '食品' },
  { label: '饮料', value: '饮料' },
  { label: '日用品', value: '日用品' },
  { label: '学习用品', value: '学习用品' }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加商品')
const formLabelWidth = '120px'

// 商品表单
const commodityForm = reactive({
  id: '',
  name: '',
  price: '',
  stock: '',
  salesVolume: 0,
  status: 'ON_SALE',
  categoryTag: [],
  image: [],
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', message: '库存必须为数字', trigger: 'blur' }
  ],
  categoryTag: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ]
}

const formRef = ref(null)
const isEdit = ref(false)

// 自定义标签相关
const inputVisible = ref(false)
const inputValue = ref('')
const tagInputRef = ref(null)

// 允许用户添加自定义标签
const showTagInput = () => {
  inputVisible.value = true
  nextTick(() => {
    tagInputRef.value.input.focus()
  })
}

// 添加自定义标签
const handleTagInputConfirm = () => {
  if (inputValue.value) {
    // 检查标签是否已存在于预设选项中
    const isExist = categoryOptions.value.some(item => item.value === inputValue.value)
    
    if (!isExist) {
      // 添加到选项列表中
      categoryOptions.value.push({
        label: inputValue.value,
        value: inputValue.value
      })
    }
    
    // 添加到当前商品的分类标签中
    if (!commodityForm.categoryTag.includes(inputValue.value)) {
      commodityForm.categoryTag.push(inputValue.value)
    }
  }
  
  inputVisible.value = false
  inputValue.value = ''
}

// 获取商品列表
const fetchCommodities = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const res = await request.get('/commodities/page', { params })
    if (res) {
      tableData.value = res.list || []
      total.value = res.total || 0
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询表单
const resetSearchForm = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchCommodities()
}

// 页面加载时获取数据
onMounted(() => {
  fetchCommodities()
})

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCommodities()
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchCommodities()
}

// 添加商品
const addCommodity = () => {
  dialogTitle.value = '添加商品'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑商品
const editCommodity = (row) => {
  dialogTitle.value = '编辑商品'
  isEdit.value = true
  
  // 深拷贝防止直接修改表格数据
  const item = JSON.parse(JSON.stringify(row))
  Object.keys(commodityForm).forEach(key => {
    if (key in item) {
      commodityForm[key] = item[key]
    }
  })
  
  // 初始化图片文件列表以便预览
  if (item.image && item.image.length > 0) {
    fileList.value = initImageFileList(item.image)
  } else {
    fileList.value = []
  }
  
  dialogVisible.value = true
}

// 删除商品
const deleteCommodity = (id) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.delete(`/commodities/${id}`)
      if (res > 0) {
        ElMessage.success('删除成功')
        fetchCommodities()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  }).catch(() => {
    // 取消删除操作
  })
}

// 上传图片的处理
const fileList = ref([])
const handleUploadSuccess = (response, file, fileList) => {
  console.log('上传成功响应:', response)
  // 响应数据结构可能是 response.data.url 或 response.data 或直接是 response
  let url = ''
  if (response && response.data && response.data.url) {
    url = response.data.url
  } else if (response && response.url) {
    url = response.url
  } else if (response && typeof response === 'object') {
    // 尝试在response对象中查找url
    url = response.url || (response.data ? response.data.url : '')
  }
  
  if (url) {
    // 检查url是否已经存在于image数组中
    if (!commodityForm.image.includes(url)) {
      commodityForm.image.push(url)
      console.log('图片URL已添加:', url)
      console.log('当前图片列表:', commodityForm.image)
    }
    // 更新文件列表中的URL
    file.url = getImageUrl(url)
  } else {
    console.error('无法从响应中获取图片URL:', response)
    ElMessage.warning('图片上传成功但无法获取URL')
  }
}

// 上传错误处理
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('文件上传失败，请重试')
}

const handleRemove = (file, fileList) => {
  const index = commodityForm.image.findIndex(url => url === file.url || getImageUrl(url) === file.url)
  if (index !== -1) {
    commodityForm.image.splice(index, 1)
  }
}

// 获取商品状态标签类型
const getStatusTagType = (status) => {
  return status === 'ON_SALE' ? 'success' : 'danger'
}

// 获取商品状态显示文本
const getStatusText = (status) => {
  return status === 'ON_SALE' ? '在售' : '下架'
}

// 图片上传前的钩子
const beforeUpload = (file) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  const isValidType = allowedTypes.includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF/WEBP 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 初始化编辑时的图片显示
const initImageFileList = (images) => {
  if (!images || !images.length) return []
  
  return images.map((url, index) => {
    return {
      name: `图片${index + 1}`,
      url: getImageUrl(url)
    }
  })
}

// 处理图片url，添加服务器地址
const getImageUrl = (url) => {
  if (!url) return ''
  return url.startsWith('/') ? SERVER_BASE_URL + url : url
}

// 获取上传请求头
const getUploadHeaders = () => {
  return {
  }
}

// 获取上传额外参数
const getUploadData = () => {
  return {
    targetDir: 'commodity' // 指定上传到commodity目录
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保分类和图片数据正确
        console.log('提交前的商品数据:', commodityForm)
        
        // 检查并处理categoryTag
        if (typeof commodityForm.categoryTag === 'string') {
          commodityForm.categoryTag = [commodityForm.categoryTag]
        } else if (!Array.isArray(commodityForm.categoryTag)) {
          commodityForm.categoryTag = []
        }
        
        // 确保image是数组
        if (!Array.isArray(commodityForm.image)) {
          commodityForm.image = []
        }
        
        // 深拷贝防止引用问题
        const formData = JSON.parse(JSON.stringify(commodityForm))
        
        let res
        if (isEdit.value) {
          // 编辑商品
          res = await request.put(`/commodities/${formData.id}`, formData)
        } else {
          // 添加商品
          res = await request.post('/commodities/add', formData)
        }
        
        if (res > 0) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          fetchCommodities()
        } else {
          ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
        }
      } catch (error) {
        console.error(isEdit.value ? '更新商品失败:' : '添加商品失败:', error)
        ElMessage.error(isEdit.value ? '更新商品失败' : '添加商品失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  // 重置为默认值
  Object.assign(commodityForm, {
    id: '',
    name: '',
    price: '',
    stock: '',
    salesVolume: 0,
    status: 'ON_SALE',
    categoryTag: [],
    image: []
  })
  
  // 清空文件列表
  fileList.value = []
}

</script>

<template>
  <div class="commodity-management">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select 
            v-model="searchForm.status"
            style="width: 100px"
            placeholder="请选择商品状态" 
            clearable
          >
            <el-option 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.categoryTag" style="width: 100px" placeholder="请选择商品分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCommodities">查询</el-button>
          <el-button @click="resetSearchForm">重置</el-button>
          <el-button type="success" @click="addCommodity">添加商品</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="商品ID" width="80" align="center" />
        <el-table-column prop="name" label="商品名称" min-width="120" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            <span>￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" align="center" />
        <el-table-column prop="salesVolume" label="销量" width="80" align="center" />
        <el-table-column prop="categoryTag" label="分类" width="120">
          <template #default="scope">
            <el-tag v-for="(tag, index) in scope.row.categoryTag" :key="index" size="small" style="margin-right: 4px">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="商品图片" width="120">
          <template #default="scope">
            <el-image 
              v-if="scope.row.image && scope.row.image.length > 0" 
              :src="getImageUrl(scope.row.image[0])" 
              style="width: 50px; height: 50px; object-fit: cover; cursor: pointer;"
              :preview-src-list="scope.row.image.map(img => getImageUrl(img))"
              :initial-index="0"
              fit="cover"
              :preview-teleported="true"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{ new Date(scope.row.createTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editCommodity(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteCommodity(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form 
        ref="formRef"
        :model="commodityForm" 
        :rules="rules" 
        label-width="100px"
        :label-position="'right'"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="commodityForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="commodityForm.price" :precision="2" :step="0.1" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="commodityForm.stock" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="销售量" prop="salesVolume">
          <el-input-number v-model="commodityForm.salesVolume" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="commodityForm.status">
            <el-radio label="ON_SALE">在售</el-radio>
            <el-radio label="OFF_SALE">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryTag">
          <div class="category-tag-container">
            <el-select 
              v-model="commodityForm.categoryTag" 
              multiple 
              placeholder="请选择商品分类" 
              style="width: 100%"
              filterable
              allow-create
              default-first-option
            >
              <el-option 
                v-for="item in categoryOptions.filter(item => item.value !== '')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            
            <div class="tag-list" v-if="commodityForm.categoryTag && commodityForm.categoryTag.length > 0">
              <p class="tag-title">已选标签:</p>
              <div class="tag-items">
                <el-tag
                  v-for="tag in commodityForm.categoryTag"
                  :key="tag"
                  closable
                  @close="commodityForm.categoryTag = commodityForm.categoryTag.filter(t => t !== tag)"
                  class="selected-tag"
                >
                  {{ tag }}
                </el-tag>
                
                <el-input
                  v-if="inputVisible"
                  ref="tagInputRef"
                  v-model="inputValue"
                  class="tag-input"
                  size="small"
                  @keyup.enter="handleTagInputConfirm"
                  @blur="handleTagInputConfirm"
                />
                
                <el-button v-else class="add-tag-button" size="small" @click="showTagInput">
                  + 添加自定义标签
                </el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            :action="`${SERVER_BASE_URL}/upload/commodity`"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-error="handleUploadError"
            :file-list="fileList"
            :data="getUploadData()"
            :headers="getUploadHeaders()"
            multiple
            name="file"
            accept="image/jpeg,image/png,image/gif,image/webp"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div v-if="commodityForm.image && commodityForm.image.length > 0" class="image-preview">
            <p>已选择 {{ commodityForm.image.length }} 张图片</p>
          </div>
          <div class="upload-tip">提示：请上传商品图片，支持JPG/PNG/GIF/WEBP格式，单张不超过5MB</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-card__body) {
  padding: 15px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.selected-label {
  margin-top: 5px;
  font-size: 12px;
  color: #409EFF;
}

.image-preview {
  margin-top: 10px;
  font-size: 14px;
  color: #409EFF;
}

.category-tag-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.tag-list {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
}

.tag-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.tag-items {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.selected-tag {
  margin-right: 6px;
  margin-bottom: 6px;
}

.tag-input {
  width: 100px;
  margin-right: 6px;
  margin-bottom: 6px;
  vertical-align: bottom;
}

.add-tag-button {
  margin-bottom: 6px;
  height: 28px;
  padding: 0 8px;
  font-size: 12px;
}
</style>